package com.blogsystem.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blogsystem.entity.Comment;
import com.blogsystem.service.CommentService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import com.blogsystem.entity.User;
import com.blogsystem.service.UserService;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Collections;
import java.util.List;

/**
 * 评论管理控制器
 */
@Controller
@RequestMapping("/api/comments")
public class CommentController {
    
    @Autowired
    private CommentService commentService;
    
    @Autowired
    private UserService userService;
    

   /**
 * 使用表单格式新增评论
 */
@PostMapping("/form")
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
public String addCommentForm(
        @RequestParam Integer articleId,
        @RequestParam String content,
        Authentication authentication,
        RedirectAttributes redirectAttributes) {

    if (authentication == null || !authentication.isAuthenticated()) {
        return "redirect:/login";
    }

    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    User user = userService.findByUsername(userDetails.getUsername());

    Comment comment = new Comment();
    comment.setArticleId(articleId);
    comment.setContent(content);
    comment.setUserId(user.getUserId());
    comment.setCreateTime(java.time.LocalDateTime.now());

    boolean success = commentService.save(comment);

    if (success) {
        redirectAttributes.addFlashAttribute("success", true);
    } else {
        redirectAttributes.addFlashAttribute("success", false);
    }

    return "redirect:/article/" + articleId;
}

    
    /**
     * 修改评论
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')") // 明确要求用户或管理员角色
    public ResponseEntity<Boolean> updateComment(@PathVariable Integer id, @RequestBody Comment comment) {
        Comment existingComment = commentService.getById(id);
        if (existingComment == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 确保用户只能修改自己的评论
        if (!isCurrentUserAuthorOfComment(existingComment)) {
            return ResponseEntity.status(403).body(false);
        }
        
        comment.setCommentId(id);
        boolean success = commentService.updateById(comment);
        return ResponseEntity.ok(success);
    }
    
    /**
     * 删除评论
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')") // 明确要求用户或管理员角色
    public ResponseEntity<Boolean> deleteComment(@PathVariable Integer id) {
        Comment comment = commentService.getById(id);
        if (comment == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 确保用户只能删除自己的评论
        if (!isCurrentUserAuthorOfComment(comment)) {
            return ResponseEntity.status(403).body(false);
        }
        
        boolean success = commentService.removeById(id);
        return ResponseEntity.ok(success);
    }
    
    /**
     * 分页查询评论（支持按文章筛选）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> listComments(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer articleId) {
        // 构建分页对象
        Page<Comment> page = new Page<>(pageNum, pageSize);
        
        // 构建查询条件
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        if (articleId != null) {
            queryWrapper.eq("article_id", articleId);
        }
        
        // 查询分页数据
        Page<Comment> commentPage = commentService.page(page, queryWrapper);
        
        // 构建返回结果
        Map<String, Object> response = new HashMap<>();
        response.put("comments", commentPage.getRecords());
        response.put("totalPages", commentPage.getPages());
        response.put("currentPage", pageNum);
        response.put("hasPrevious", pageNum > 1);
        response.put("hasNext", pageNum < commentPage.getPages());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取评论详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Comment> getCommentById(@PathVariable Integer id) {
        Comment comment = commentService.getById(id);
        if (comment == null) {
            return ResponseEntity.notFound().build();
        }
        
        return ResponseEntity.ok(comment);
    }

    /**
     * 检查当前用户是否是评论的作者
     */
    private boolean isCurrentUserAuthorOfComment(Comment comment) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }
        
        String currentUsername = authentication.getName();
        User user = userService.findByUsername(currentUsername);
        return user != null && user.getUserId().equals(comment.getUserId());
    }
}